<template>
	<view class="full-screen flex-column flex-center bg-light">
		<view v-if="!writing" class="fill-parent">
			<view class="w-100 h-90vh flex-column flex-center">
				<image :src="picture" @click="writing = true" :style="canvasStyle"></image>
			</view>
			<view class="pos-fixed bottom-0p bg-white w-100 flex-row align-center justify-around pdtb-5">
				<view v-for="(item, idx) in options" :key="idx" class="flex-column flex-center pd-5"
					@click="selectOption(item,idx)">
					<image src="../../static/editImage/biaoji.png" mode="" style="width: 60rpx;height:60rpx"></image>
					<!-- 	<yl-icon :icon="item.icon" size="size-22" color="text-black"></yl-icon> -->
					<text class=" text-black mgt-2" style="font-size: 15px;">{{item.label}}</text>
				</view>
			</view>
		</view>
		<view v-else class="full-screen">
			<view class="h-75vh flex-column flex-center">
				<ylGraffiti ref="graffiti" canvas-id="myCanvas" :width="canvasStyle.w" :height="canvasStyle.h" :shape="curShape"
					:lineColor="lineColor" :lineWidth="lineSize" :bgImage="picture" @stepChanged="stepChanged" @penEnd="penEnd"
					@repeal="repeal" @redo="redo">
				</ylGraffiti>
			</view>
			<!-- h-25vh  -->
			<view class="w-100 pos-fixed bottom-0p bg-white pdtb-5 flex-column justify-between" style="">
				<view v-if="optIndex == 0" class="flex-row align-center justify-around mglr-50 pdb-5" style="height: 9vh;">
					<view v-for="(item, idx) in shapes" :key="idx" @click="updateShape(item, item.shape, idx)">
						<!-- 暂时不删除 后续需要打开即可 -->
						<!-- <view v-if="item.shape == 'rect' " style="width: 18px;height: 18px;border:2px solid red"
							:class="[item.active ? 'bg-blue': 'bg-u-main', {'round': item.shape == 'circle', 'radius-2': item.shape == 'rect'}]">
						</view> -->
						<!-- v-else  -->
						<view class="" style="">
							<!-- 暂时不删除 后续需要打开即可 -->
							<!-- 	<yl-icon :icon="item.icon" :size="item.size || 'size-22'"
								:color="item.active ? 'text-blue': 'text-black'"></yl-icon> -->
							<!-- 画笔 -->
							<u-icon v-if="item.shape==='curve'" name="edit-pen-fill" :color="item.active? '#0081FF': ''"
								size="27"></u-icon>
							<!-- 横线 -->
							<u-icon v-if="item.shape==='line'" name="minus" :color="item.active? '#0081FF': ''" size="27"></u-icon>
							<!-- 矩形 -->
							<image v-if="item.shape==='hollow-rect' &&  item.active" src="../../static/editImage/juxing-on.png"
								mode="" style="width: 48rpx;height:48rpx;margin-top: 8rpx;"></image>
							<image v-if="item.shape==='hollow-rect' &&  !item.active" src="../../static/editImage/juxing-off.png"
								mode="" style="width: 48rpx;height:48rpx;margin-top: 8rpx;"></image>
							<!-- 圆形填充 -->
							<uni-icons v-if="item.shape==='circle'" type="smallcircle-filled" size="27"
								:color="item.active?  '#0081FF': ''"></uni-icons>
							<!-- 圆形空心 -->
							<uni-icons v-if="item.shape==='hollow-circle'" type="circle" size="27"
								:color="item.active?  '#0081FF': ''"></uni-icons>
						</view>

					</view>
				</view>

				<!-- 颜色区块 颜色区块 颜色区块 颜色区块 颜色区块 颜色区块 颜色区块 颜色区块 颜色区块 颜色区块 颜色区块 height: 9vh;-->
				<view v-if="optIndex == 1" class=" " style="margin-bottom: 30rpx;padding: 0 10rpx;">
					<view class="lxy-content">
						<scroll-view scroll-x="true" class="content-scroll" scroll-with-animation :scroll-left="scrollLeft">
							<view v-for="(item, idx) in colors" :key="idx" class="scroll-item"
								style="width:100rpx;height:90rpx;margin-bottom: 20rpx;margin-right: 20rpx;"
								:style="'background-color:' + item.color" :class="{'solids': item.active}"
								@click="updateColor(item.color, idx)">
								<!-- {{item.name}} -->
							</view>
						</scroll-view>
					</view>
					<!-- 暂时不删除 后续需要打开即可 -->
					<!-- 	<view  class="flex-1 " :class="{'solids': item.active}"
						style="width:100rpx;height:90rpx;margin-bottom: 20rpx;margin-right: 20rpx;"
						:style="'background-color:' + item.color" @click="updateColor(item.color, idx)">
					</view> -->
				</view>
				<view v-if="optIndex == 2" class="flex-row align-center justify-around mglr-50 pdb-5" style="height: 9vh;">
					<view v-for="(item, idx) in sizes" :key="idx" class="square-20p flex-row flex-center"
						@click="updateSize(item.thickness, idx)">
						<view class="round" :class="{'bg-u-info-disabled': !item.active, 'bg-blue': item.active}"
							:style="'width:'+item.thickness+'px;height:'+item.thickness+'px'">
						</view>
					</view>
				</view>
				<view v-if="optIndex == 3" class="flex-row align-center justify-around mglr-30" style="height: 9vh;">
				</view>
				<view class="flex-row align-center justify-around mglr-20" style="height: 8vh;">
					<view v-for="(item, idx) in writingOptions" :key="item.label" class="flex-column flex-center pd-5" style=""
						@click="selectWritingOption(item,idx)">
						<view class="square-25p flex-row flex-center"
							:class="{'solid border-blue round': optIndex == 1 && optIndex == idx}">
							<yl-icon v-if="item.label==='清空'" :icon="item.icon"
								:size="optIndex == 1 && optIndex == idx ? 'size-18 lh-1': 'size-22'"
								:color="idx == 1 ? lineColor: optIndex == idx ? 'text-blue': item.color"></yl-icon>
							<image v-if="item.label==='重做' && item.color==='text-gray'" src="../../static/editImage/chongzuo-off.png"
								mode="" style="width: 48rpx;height:48rpx"></image>
							<image v-if="item.label==='重做' && item.color==='text-black'" src="../../static/editImage/chongzuo-on.png"
								mode="" style="width: 48rpx;height:48rpx"></image>
							<image v-if="item.label==='撤销' && item.color==='text-gray'" src="../../static/editImage/chexiao-off.png"
								mode="" style="width: 48rpx;height:44rpx"></image>
							<image v-if="item.label==='撤销' && item.color==='text-black'" src="../../static/editImage/chexiao-on.png"
								mode="" style="width: 48rpx;height:44rpx"></image>
							<uni-icons v-if="item.label==='粗细' && item.color==='text-black'" type="smallcircle" size="27"
								:color="thicknessColor"></uni-icons>
							<uni-icons v-if="item.label==='颜色' && item.color==='text-black'" type="circle-filled" size="27"
								:color="color"></uni-icons>
							<u-icon v-if="item.label==='涂鸦' && item.color==='text-black'" name="edit-pen-fill" :color="GraffitiColor"
								size="27"></u-icon>
						</view>
						<text class="text-sm mgt-2"
							:class="[{'text-blue': optIndex == idx}, optIndex != idx ? item.color: '']">{{item.label}}</text>
					</view>
				</view>
				<view class="flex-row align-center justify-between padding-lr pdtb-5 mgt-15 mgb-10" style="height: 8vh;">
					<uni-icons type="closeempty" size="30" color="'#523339'" @click="writing = false"></uni-icons>
					<!-- <yl-icon icon="cuicon-close" size="size-28" color="text-black" @click="writing = false"></yl-icon> -->
					<text class=" text-black" style="font-size: 15px;">标记</text>
					<uni-icons type="checkmarkempty" size="30" color="'#523339'" @click="savePicture"></uni-icons>
					<!-- <yl-icon icon="cuicon-check" size="size-28" color="text-black" customClass="pdlr-5 pdtb-2"
						@click="savePicture"></yl-icon> -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import ylGraffiti from "@/components/yl-graffiti/yl-graffiti.vue";
	import form from "../../uni_modules/uview-ui/libs/config/props/form";
	import image from "../../uni_modules/uview-ui/libs/config/props/image";
	export default {
		components: {
			ylGraffiti
		},
		data() {
			return {
				thicknessColor: "", //粗细
				color: "", //颜色
				GraffitiColor: "", //涂鸦颜色
				lineColorS: "",
				title: '标记',
				picture: "",
				writing: false,
				swiperCurrent: -1,
				canvasStyle: {},
				optIndex: 0,
				options: [{
						label: "标记",
						icon: "cuicon-write"
					},
					/* {
										label: "删除",
										icon: "cuicon-delete"
									} */
				],
				category: [{
						id: 1,
						name: '星期一'
					},
					{
						id: 2,
						name: '星期二'
					},
					{
						id: 3,
						name: '星期三'
					},
					{
						id: 4,
						name: '星期四'
					},
					{
						id: 5,
						name: '星期五'
					},
					{
						id: 6,
						name: '星期六'
					},
					{
						id: 7,
						name: '星期七'
					},
					{
						id: 8,
						name: '星期八'
					},
					{
						id: 9,
						name: '星期九'
					},
					{
						id: 10,
						name: '星期十'
					}
				],
				contentScrollW: 0, // 导航区宽度
				curIndex: 0, // 当前选中
				scrollLeft: 0, // 横向滚动条位置
				shapes: [ //画笔形状
					{
						icon: "cuicon-write", //画笔
						shape: "curve",
						active: true
					},
					{
						icon: "cuicon-move",
						shape: "line",
						active: false
					},
					{
						icon: "cuicon-square",
						shape: "rect",
						active: false
					},
					{
						icon: "cuicon-square",
						shape: "hollow-rect",
						active: false
					},
					{
						icon: "cuicon-round",
						shape: "circle",
						active: false
					},
					{
						icon: "cuicon-round",
						shape: "hollow-circle",
						active: false
					}
				],
				colors: [ //画笔颜色 
					{
						color: "#ff0000",
						active: true
					},
					{
						color: "#1c9d02",
						active: false
					},
					{
						color: "#000000",
						active: false
					},
					{
						color: "#006ce6",
						active: false
					},
					{
						color: "#efaa03",
						active: false
					},
					{
						color: "#FFFF00",
						active: false
					},
					{
						color: "#00FFFF",
						active: false
					},
					{
						color: "#FF00FF",
						active: false
					},
					{
						color: "#00FF01",
						active: false
					},

				],
				sizes: [ //画笔粗细
					{
						thickness: 3,
						active: true
					},
					// {
					// 	thickness: 3,
					// 	active: true
					// },
					{
						thickness: 6,
						active: false
					},
					// {
					// 	thickness: 5,
					// 	active: true
					// },
					{
						thickness: 9,
						active: false
					},
					// {
					// 	thickness: 7,
					// 	active: true
					// },
					{
						thickness: 12,
						active: false
					},
					// {
					// 	thickness: 9,
					// 	active: true
					// },
					{
						thickness: 15,
						active: false
					},
					// {
					// 	thickness: 12,
					// 	active: false
					// },
					// {
					// 	thickness: 14,
					// 	active: false
					// }
				],
				stepInfo: {
					curStep: -1,
					len: 0
				},
				saving: false,
				systemInfo: null,
				oldPicture: '',
				type: '',
				index: 0,
				drawLength: null,
				chongzuo: "",
				chexiao: ""
			}
		},
		onShow() {
			// 默认不惦记标记 打开编辑图片菜单区域
			this.writing = true;
			this.GraffitiColor = "#0081FF" //打开时默认涂鸦选中
		},
		onLoad(query) {

			this.systemInfo = uni.getSystemInfoSync();
			this.type = query.type
			this.index = query.index
			// console.log('开始编辑图片了', query, this.type, this.index)
			uni.getImageInfo({
				src: query.picture,
				success: image => {
					console.log(image);
					this.canvasStyle = this.caclCanvasStyle(image.height, image.width);
					this.picture = query.picture
					this.oldPicture = query.picture
					console.log('获取picture', this.picture)
				},
				fail: err => {
					console.log("getImageInfo err: ", err);
				}
			});
		},
		computed: {
			/**
			 * 涂鸦操作项
			 */
			writingOptions() {
				const {
					curStep,
					len
				} = this.stepInfo;
				return [{
					label: "涂鸦",
					icon: "cuicon-write",
					color: 'text-black'
				}, {
					label: "颜色",
					icon: "cuicon-radioboxfill",
					color: 'text-black'
				}, {
					label: "粗细",
					icon: "cuicon-radiobox",
					color: 'text-black'
				}, {
					label: "撤销",
					icon: "cuicon-repeal",
					color: curStep == -1 ? 'text-gray' : 'text-black'
				}, {
					label: "重做",
					icon: "cuicon-repeal transform-180",
					color: curStep == len - 1 ? 'text-gray' : 'text-black'
				}, {
					label: "清空",
					icon: "custom-icon-clear",
					color: curStep == -1 ? 'text-gray' : 'text-black'
				}]
			},

			/**
			 * 当前形状
			 */
			curShape() {
				return this.shapes.filter(shape => shape.active)[0].shape;
			},

			/**
			 * 线条颜色
			 */
			lineColor() {
				return this.colors.filter(color => color.active)[0].color;
			},

			/**
			 * 线条粗细
			 */
			lineSize() {
				return this.sizes.filter(size => size.active)[0].thickness;
			},
		},
		methods: {
			scroll: function(e) {
				console.log(e)
			},
			// 画完
			penEnd(canvasData) {
				console.log('储存画完了', canvasData)
				this.drawLength = canvasData
				// this.canvasData = canvasData
				// // 清空重做高亮显示
				// this.fiveSrc = "../../static/editImage/chongzuo-off.png" //重做
				// this.threeSrc = "../../static/editImage/chexiao-on.png" //撤销

			},
			// 撤銷
			repeal(data) {
				console.log('撤銷了', data)
			},

			// 重做
			redo(data) {
				console.log('重做了', data)
			},

			/**
			 * 选择图片
			 */
			choseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'] //拍照或从相册选择
				}).then(res => {
					const picture = res[1].tempFiles[0].path;
					uni.getImageInfo({
						src: picture,
						success: image => {
							console.log(image);
							this.canvasStyle = this.caclCanvasStyle(image.height, image.width);
							this.picture = picture;
						},
						fail: err => {
							console.log("getImageInfo err: ", err);
						}
					});
				}).catch(res => {})
			},

			/**
			 * 计算高
			 * @param {Object} imgHeight
			 * @param {Object} imgWidth
			 */
			caclCanvasStyle(imgHeight, imgWidth) {
				let width = 0,
					height = 0;

				if (imgWidth > imgHeight) {
					if (this.systemInfo.windowWidth <= imgWidth) {
						width = this.systemInfo.windowWidth;
						height = (this.systemInfo.windowWidth / imgWidth) * imgHeight;
					} else {
						width = imgWidth;
						height = imgHeight;
					}
				} else {
					if (this.systemInfo.windowHeight * 0.7 <= imgHeight) {
						height = this.systemInfo.windowHeight * 0.7;
						width = (this.systemInfo.windowHeight * 0.7 / imgHeight) * imgWidth;
						if (this.systemInfo.windowWidth <= width) {
							width = this.systemInfo.windowWidth * 0.8;
							height = (this.systemInfo.windowWidth * 0.8 / width) * height;
						}
					} else {
						width = imgWidth;
						height = imgHeight;
					}
				}

				return {
					width: width.toFixed(0) + "px",
					height: height.toFixed(0) + "px",
					w: parseInt(width.toFixed(0)),
					h: parseInt(height.toFixed(0)),
					style: `width:${width.toFixed(0)}px;height:${height.toFixed(0)}px;`
				}
			},

			/**
			 * 图片操作
			 * @param {Object} index
			 */
			selectOption(item, index) {
				console.log('标记点击', item, index, this.GraffitiColor)
				switch (index) {
					case 0:
						this.writing = true;
						this.GraffitiColor = "#0081FF" //打开时默认涂鸦选中
						break;
					case 1:
						this.picture = "";
						break;
					default:
						break;
				}
			},

			/**
			 * 选择涂鸦的类型
			 * @param {Object} index
			 */
			selectWritingOption(item, index) {
				console.log('点击的是', item, index)
				if (index == 0) {
					this.color = ""
					this.GraffitiColor = "#0081FF"
				} else {
					this.GraffitiColor = ""
				}
				if (index == 1) this.color = "#0081FF"
				if (index == 0 || index == 1) this.thicknessColor = ""
				if (index == 2) {
					this.thicknessColor = "#0081FF"
					this.color = "" //清空颜色选中
				}

				switch (index) {
					case 0:
					case 1:
					case 2:
						this.optIndex = index;
						break;
					case 3:
						this.$refs.graffiti.repeal();
						break;
					case 4:
						this.$refs.graffiti.redo();
						break;
					case 5:
						this.$refs.graffiti.clearBoard();
						break;
					default:
						break;
				}
			},

			/**
			 * 当前位置变化
			 * @param {Object} e
			 */
			stepChanged(e) {
				console.log('当前位置变化', e)
				this.stepInfo = e;
			},

			/**
			 * 更新线条形状
			 * @param {Object} shape
			 * @param {Object} index
			 */
			updateShape(item, shape, index) {
				console.log('选择的形状', item, shape, index, this.shapes)
				this.shapes.forEach((item, idx) => item.active = idx == index);
			},

			/**
			 * 更新线条颜色
			 * @param {Object} color
			 * @param {Object} index
			 */
			updateColor(color, index) {
				this.colors.forEach((item, idx) => item.active = idx == index);
			},

			/**
			 * 更新线条尺寸
			 * @param {Object} size
			 * @param {Object} index
			 */
			updateSize(size, index) {
				this.sizes.forEach((item, idx) => item.active = idx == index);
			},

			/**
			 * 保存涂鸦
			 */
			savePicture() {
				// uni.showLoading({
				// 	mask: true
				// });
				this.$refs.graffiti.saveCanvas().then(async res => {
					this.picture = res;
					this.writing = false;
					console.log('获取syncsaveCanvas结果', res);
					let $url = "http://api.test.zytsaas.com/"
					uni.uploadFile({
						url: $url + `Base_Manage/Upload/OssUploadFileByForm`,
						// ?ObjectKey=${strFileName}
						filePath: res,
						name: 'file',
						header: {
							'Authorization': uni.getStorageSync('tokenKey')
						},
						formData: {
							fileDir: "uploads",
							fileName: res.substring(0, res
								.lastIndexOf("/")),
							storeType: 6,
						}
					}).then(response => {
						console.log('获取最终返回的-----------------图片canvvas路径', response)
						let [error, res] = response;
						let result = JSON.parse(res.data)
						let savedFilePath = result.Url

						var imglist = []
						var obj = {}
						var newImgList = []
						if (this.type == 'local') imglist = JSON.parse(uni.getStorageSync('localImgList'))
						else if (this.type == 'upload') {
							obj = JSON.parse(uni.getStorageSync('uploadImgList'))
							imglist = obj.content
						} else {
							this.type == 'edit'
							obj = JSON.parse(uni.getStorageSync('editImgList'))
							imglist = obj.content
						}

						if (this.type == 'edit') {
							console.log('匹配到edit这里了', this.type)
							newImgList = JSON.parse(uni.getStorageSync('editImgList')).content
							newImgList[this.index].Murl = savedFilePath
							// uni.setStorageSync('editImgList', JSON.stringify(newImgList))
							// this.$store.commit('setImageList', newImgList)
							console.log('打印匹配到edit这里的缓存imglisnewImgListnewImgListnewImgListnewImgListt数组', newImgList, this
								.index)
							// uni.setStorageSync('editLocalImgList', JSON.stringify(newImgList))
						} else {
							if (imglist.length > 1) {
								imglist[this.index].Murl = savedFilePath
								console.log('匹配到大于1', imglist)
							} else {
								imglist[0].Murl = savedFilePath
								console.log('匹配到其他', imglist)
							}
						}

						if (this.type == 'local') {
							uni.setStorageSync(
								'localImgList', JSON.stringify(imglist))
							console.log('匹配到这里处理local', obj, imglist)
						} else if (this.type == 'upload') {
							obj.content = imglist
							uni.setStorageSync('uploadImgList', JSON
								.stringify(obj))
							let formArr = JSON.parse(uni.getStorageSync('fromdata'))
							formArr[obj.vix].imglist = imglist
							uni.setStorageSync('fromdata', JSON.stringify(
								formArr))
							console.log('匹配到这里处理upload', obj, imglist)
						} else {
							// obj.content = imglist
							let newObj = {
								Murl: newImgList[this.index].Murl,
								name: newImgList[this.index].name,
								index: this.index
							}
							// uni.setStorageSync('editImgList', JSON.stringify(newObj))
							// let formArr = JSON.parse(uni.getStorageSync('fromdata'))
							// // formArr[obj.vix].imglist = newImgList
							// // uni.setStorageSync('fromdata', JSON.stringify(formArr))
							// console.log('匹配到这里处理edit',formArr,  obj)
							console.log('返回之前edit类型', newObj)
							this.$store.commit('setImageList', newObj)
						}

						// 返回上一页
						uni.navigateBack()

					})

					// console.log('获取最终保存涂鸦缓存里的图片数组', this.type, imglist, JSON.parse(uni.getStorageSync('editImgList')));
					// uni.removeSavedFile({
					// 	filePath: this.oldPicture,
					// 	success: (result) => {
					// 		console.log('删除成功');
					// 		uni.saveFile({
					// 			tempFilePath: res,
					// 			success: (val) => {
					// 				console.log('uni.saveFile方法结果', val.savedFilePath);
					// 				imglist[this.index].Murl = val.savedFilePath
					// 				if (this.type == 'local') uni.setStorageSync(
					// 					'localImgList', JSON.stringify(imglist))
					// 				else if (this.type == 'upload') {
					// 					obj.content = imglist
					// 					uni.setStorageSync('uploadImgList', JSON
					// 						.stringify(obj))
					// 					let formArr = JSON.parse(uni.getStorageSync(
					// 						'fromdata'))
					// 					formArr[obj.vix].imglist = imglist
					// 					uni.setStorageSync('fromdata', JSON.stringify(
					// 						formArr))
					// 				}
					// 				// 返回上一页
					// 				uni.navigateBack()
					// 			},
					// 			complete: () => {
					// 				uni.hideLoading()
					// 			}
					// 		});
					// 	},
					// 	fail: (err) => {
					// 		console.log(err);
					// 	}
					// })
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	/*颜色区块横向滚动操作*/
	.lxy-content {
		// width: 100%;
		// height: 100rpx;
		box-sizing: border-box;

		// position: fixed;
		// top: 445rpx;
		.content-scroll {
			height: 100rpx;
			white-space: nowrap;

			.scroll-item {
				width: 64rpx;
				height: 64rpx;
				line-height: 62rpx;
				background: #FFFFFF;
				border-radius: 10rpx;
				display: inline-block;
				text-align: center;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 400;
				color: #666666;
				margin-left: 28rpx;
				padding: 0 24rpx;

				&.active {
					background: #2851F3;
					color: #FFFFFF;
				}
			}

			.scroll-item:last-child {
				margin-right: 28rpx;
			}
		}
	}
</style>